﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Mt.Site.Core.WorkFlows.Process.Entities;
using Mt.Site.Core.WorkFlows.Process.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mt.Site.Core.WorkFlows.Process.Stores
{
    internal class WokFlowLogStore : IWokFlowLogStore, ITransientDependency
    {
        private readonly IRepository<WorkFlowLogs, long> _workFlowLogsRepository;
        public IObjectMapper ObjectMapper { get; set; }

        public WokFlowLogStore(IRepository<WorkFlowLogs, long> workFlowLogsRepository)
        {
            _workFlowLogsRepository = workFlowLogsRepository;
            ObjectMapper = NullObjectMapper.Instance;
        }

        public async Task<List<WorkFlowLogDto>> GetLogDataAsync(Guid paperId)
        {
            var list = await _workFlowLogsRepository.GetAllListAsync(c => c.PaperId == paperId);
            return ObjectMapper.Map<List<WorkFlowLogDto>>(list).OrderBy(c => c.CreationTime).ToList();
        }

        public async Task AddLogAsync(string message, string fromOperator, string nextOperator, Guid paperId, Guid? processId)
        {
            var entity = new WorkFlowLogs
            {
                Message = message,
                FromOperator = fromOperator,
                NextOperator = nextOperator,
                PaperId = paperId,
                ProcessId = processId
            };
            await _workFlowLogsRepository.InsertAsync(entity);
        }

        public async Task RemoveLogAsync(Guid paperId, Guid processId)
        {
            await _workFlowLogsRepository.DeleteAsync(c => c.PaperId == paperId && c.ProcessId == processId && c.Parallel == false);
        }

        public async Task AddLogWithParallelAsync(string message, string fromOperator, string nextOperator, Guid paperId, Guid? processId)
        {
            var entity = new WorkFlowLogs
            {
                Message = message,
                FromOperator = fromOperator,
                NextOperator = nextOperator,
                PaperId = paperId,
                ProcessId = processId,
                Parallel = true
            };
            await _workFlowLogsRepository.InsertAsync(entity);
        }

        public async Task RemoveLogWithParallelAsync(Guid paperId, Guid processId)
        {
            await _workFlowLogsRepository.DeleteAsync(c => c.PaperId == paperId && c.ProcessId == processId);
        }
    }
}
